package com.yhx.security.gfoBank.api.com.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Base64;

import com.yhx.security.gfoBank.api.com.gmcrypto.mf.gm.SM4Util;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.RandomStringUtils;



public class SM2RequestTestJSON {

	public static void main(String[] args) {
		try{
			String merchantPriKey="test001.pvk";
			String merchantPubKey="test001.puk";

			String guangfaPubKey="D:\\Coding\\threadStudy\\src\\main\\webapp\\cgb-open.puk";
			String encoding="GBK";

			String path=SM2RequestTestXML.class.getClassLoader().getResource("").getPath();
			System.err.println(path);
			File file=new File("D:\\Coding\\threadStudy\\src\\main\\java\\com\\yhx\\security\\gfoBank\\api\\json\\sendMsgCode.json");
			FileInputStream fi=new FileInputStream(file);
			BufferedReader bf=new BufferedReader(new InputStreamReader(fi));
			StringBuffer strBuffer=new StringBuffer();
			String line=null;
			while( (line=bf.readLine())!=null){
				strBuffer.append("\n").append(line);
			}
			String reqStr=strBuffer.substring(1);
			System.out.println("请求报文原文：\n"+reqStr);


			String contentType="application/json";

			//1、签名

			String signature=SM2RequestTestXML.sign(reqStr,merchantPriKey,encoding);
			System.out.println("请求报文签名结果：\n"+signature);
			String certId= MD5.getMD5(merchantPubKey);

			//2、加密
			RandomStringUtils rs = new RandomStringUtils();
			String verifyChars = "123457890abcdefghijklmnopqrstuvwxyz";
			String encryptKey = rs.random(16, verifyChars).toUpperCase();
			System.out.println("encryptKey="+encryptKey);
			byte[] encryptBytes= SM4Util.encryptCBC(reqStr.getBytes(encoding), encryptKey.getBytes(), encryptKey.getBytes());
			reqStr=Base64.getEncoder().encodeToString(encryptBytes);

			System.out.println("请求报文加密结果：\n"+reqStr);

			//3、使用广发公钥对密码进行加密
			String encryptKey1=SM2RequestTestXML.sm2EncryptString(encryptKey, guangfaPubKey, encoding);

			//4、发生post请求
			String requestUrl="http://218.13.4.182:8089/gateway/API/lifeValue/updateCouponCode/1.0.0";
			PostMethod postMethod = new PostMethod(requestUrl);


			//mock
			/*String result=reqStr;
			String respSignature=signature;*/
			HttpClient httpClient = new HttpClient();
		    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		    httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);

		    postMethod.setRequestHeader("signature",signature);
		    postMethod.setRequestHeader("signType","SM2");
		    postMethod.setRequestHeader("encryptType","SM4");
		    postMethod.setRequestHeader("encryptKey",encryptKey1);
		    postMethod.setRequestHeader("certId",certId);

		    StringRequestEntity sre = new StringRequestEntity(reqStr, contentType,encoding);
		    postMethod.setRequestEntity(sre);
		    String result=null;
		    String respSignature=null;
		    try{
		    	int status=httpClient.executeMethod(postMethod);
		    	if (status == HttpStatus.SC_OK) {
		    		result=postMethod.getResponseBodyAsString();
					System.out.println(result);
		    		respSignature=postMethod.getResponseHeader("signature").getValue();
		    	}else{
		    		System.out.println("HTTPException HttpStatus:"+status);
		    	}
		    }catch (IOException e) {
		    	e.printStackTrace();
		    }

		    System.out.println("返回报文：\n"+result);

		    //5、解密
		     byte[] decryptBytes=SM4Util.decryptCBC(Base64.getDecoder().decode(result), encryptKey.getBytes(), encryptKey.getBytes());
		     String respStr=new String(decryptBytes,encoding);
		     System.out.println("返回报文解密结果：\n"+respStr);

		    //6、验签
		    boolean veryfyResult=SM2RequestTestXML.veryfySign(respStr, respSignature, guangfaPubKey, encoding);
		    System.out.println("返回报文验签结果：\n"+veryfyResult);


		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
}
